'use strict';
'require view';
'require ui';
'require form';
'require network';
'require rpc';

function handlePage(ev) {
	var filter = document.querySelector('input[name="filter"]'),
		pager = ev.target.parentNode,
		offset = +pager.getAttribute('data-offset'),
		next = ev.target.classList.contains('next');

	if ((next && (offset + 100) >= currentDisplayRows.length) ||
		(!next && (offset < 100)))
		return;

	offset += next ? 100 : -100;
	pager.setAttribute('data-offset', offset);
	pager.querySelector('.text').firstChild.data = currentDisplayRows.length
		? _('Displaying %d-%d of %d').format(1 + offset, Math.min(offset + 100, currentDisplayRows.length), currentDisplayRows.length)
		: _('No packages');

	if (offset < 100)
		pager.querySelector('.prev').setAttribute('disabled', 'disabled');
	else
		pager.querySelector('.prev').removeAttribute('disabled');

	if ((offset + 100) >= currentDisplayRows.length)
		pager.querySelector('.next').setAttribute('disabled', 'disabled');
	else
		pager.querySelector('.next').removeAttribute('disabled');

	var placeholder = _('No information available');

	if (filter.value)
		placeholder = [
			E('span', {}, _('No packages matching "<strong>%h</strong>".').format(filter.value)), ' (',
			E('a', { href: '#', onclick: 'handleReset(event)' }, _('Reset')), ')'
		];

	cbi_update_table('#packages', currentDisplayRows.slice(offset, offset + 100),
		placeholder);
}

/**
 * 
 * @param {object} networks 
 * @param {object} hosthints 
 * @returns {Object}
 */
let renderData = (networks, hosthints) => {

	let deviceData = {};

	for (var i = 0; i < networks.length; i++) {
		for (var k = 0; k < networks[i].assoclist.length; k++) {
			var bss = networks[i].assoclist[k],
				name = hosthints.getHostnameByMACAddr(bss.mac);

			if (!name || name == '?') {
				continue;
			}
			deviceData[name] = hosthints.getIPAddrByMACAddr(bss.mac);
		}
	}
	return deviceData;
};


return view.extend({

	load: () => {
		return Promise.all([
			network.getWifiNetworks(),
			network.getHostHints()
		]).then((radios_networks_hints) => {
			var tasks = [];

			for (var i = 0; i < radios_networks_hints[0].length; i++)
				tasks.push(L.resolveDefault(radios_networks_hints[0][i].getAssocList(), []).then(L.bind(function (net, list) {
					net.assoclist = list.sort(function (a, b) { return a.mac > b.mac });
				}, this, radios_networks_hints[0][i])));

			return Promise.all(tasks).then(function () {
				return radios_networks_hints;
			});
		})
	},


	render: (data) => {

		/**  
		 * @var {Object}
		 * */                                                                                                                    
		let deviceData = renderData(data[0], data[1]); 
		console.log(deviceData);
		var m, s, o; 
		m = new form.Map('jump', _('Jump times')); 
		s = m.section(form.GridSection, 'domain', _('Host entries')); 
		s.addremove = true; 
		s.anonymous = true; 
		s.sortable = true; 
		o = s.option(form.ListValue, 'hostname', _('Hostname')); 
		s.anonymous = true; s.dynamic = true; 
		o.value("", _("Please select")); 
		for (let key in deviceData) { 
			o.value(key, key); 
		}
		o.onchange = (res, i, value) => {
			 console.log(i); console.log(value); console.log(res); 
			 let inputElement = res.
			 	target.parentElement.parentElement.nextSibling.querySelector("input");
			console.log(res.target.parentElement); console.log(inputElement); 
			let id = inputElement.id; 
			if (-1 === id.indexOf("ipaddress")) { 
				return; 
			} 
			inputElement.value = deviceData[value]; 
		}                                                                                                                                                                                                                                                                                                                                                                   
		o = s.option(form.Value, 'ipaddress', _('IP address')); 
		o.datatype = 'ipaddress'; o.rmempty = true;
		o = s.option(form.Value, 'jumpTimes', _('Jump times')); 
		o.datatype = 'jumptimes'; o.rmempty = true; 
		return m.render();
	}
});